package com.ruoyi.celoan.handanUtils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.SM2;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.celoan.entity.ExTradeEffectEnterprisesDetailSqsEntity;
import com.ruoyi.celoan.handanUtils.request.HanDanDataRequest;
import com.ruoyi.celoan.handanUtils.request.HanDanDataSelectRequest;
import com.ruoyi.celoan.handanUtils.response.CountryPlatformResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.mime.ContentBody;
import org.apache.hc.client5.http.entity.mime.FileBody;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.entity.mime.StringBody;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedInputStream;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class HanDanHttpSelectUtilsNew {
    private static final Logger log = LoggerFactory.getLogger(HanDanHttpSelectUtilsNew.class);
    public static final String myPublicKey = "049ecc3b71e8e43ae240298f9f55de4b9ad3733236ad5a3782448fe8a7d0a22f8b116c98dd9904871037d20b131b1b4d8165ef534f25205d628c5474448b5fc15e";
    public static final String myPrivateKey = "00969996be634b00d61a465f27403d0e7346d9d930d008d0f19f840604e89592dc";

    public CountryPlatformResponse updateUser(String url, String json) {
        return null;
    }

    public static CountryPlatformResponse gwyTaxArrears(String json, String token) {
        String url = "/api/creditInquiry/gwyTaxArrears";
        HanDanDataSelectRequest request = HanDanBean.jiaMiChaXunPort(json, token);
        return post(url, request);
    }

    public static CountryPlatformResponse post(String url, HanDanDataSelectRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("txnBodyCom", request);
        Map<String, Object> txnCommCom = new HashMap<>();
        txnCommCom.put("txnIttChnlId", "99990001000000000000000");
        txnCommCom.put("txnIttChnlCgyCode", "99999999");
        map.put("txnCommCom", txnCommCom);
        log.info("请求参数:" + JSONObject.toJSONString(map));
        log.info("请求接口地址" + HanDanHttpUtils.apiUrl + url);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", "application/json;charset=UTF-8");
        headers.set("Referer", HanDanHttpUtils.apiUrl);
        org.springframework.http.HttpEntity<String> requestEntity = new org.springframework.http.HttpEntity(JSONObject.toJSONString(map), (MultiValueMap) headers);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        ResponseEntity<String> response = restTemplate.postForEntity(HanDanHttpUtils.apiUrl + url, requestEntity, String.class, new Object[0]);
        String responseStr = (String) response.getBody();
        log.info("返回结果:" + responseStr);
        JSONObject jsonObject = JSONObject.parseObject(responseStr);
        String result = jsonObject.getString("C-API-Status");
        CountryPlatformResponse countryPlatformResponse = (CountryPlatformResponse) jsonObject.getObject("C-Response-Body", CountryPlatformResponse.class);
        if (!ObjectUtil.isNotNull(countryPlatformResponse)) {
            countryPlatformResponse = new CountryPlatformResponse();
        }
        if (StringUtils.equals("00", result)) {
            countryPlatformResponse.setApiStatus(true);
            SM2 sm2 = SmUtil.sm2(myPrivateKey, myPublicKey);
            String responseData = HanDanBean.dealResult(sm2, countryPlatformResponse);
            log.info("结果:::::" + responseData);
            countryPlatformResponse.setData(responseData);
        } else {
            countryPlatformResponse.setApiStatus(false);
        }
        return countryPlatformResponse;
    }

    public static CountryPlatformResponse sendUploadLicense(String url, ExTradeEffectEnterprisesDetailSqsEntity model, String token) {
        String responseStr = "";
        File file = new File(model.getFileUrl());
        if (!file.exists()) {
            CountryPlatformResponse countryPlatformResponse = new CountryPlatformResponse();
            log.info("没有找到文件");
            countryPlatformResponse.setApiStatus(false);
            return countryPlatformResponse;
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        StringBody enterpriseName = new StringBody(model.getEnterpriseName(), ContentType.APPLICATION_JSON);
        StringBody uniscId = new StringBody(model.getUniscId(), ContentType.APPLICATION_JSON);
        StringBody authorizedInfos = new StringBody(model.getAuthorizedInfos(), ContentType.APPLICATION_JSON);
        StringBody authorizedOrgsCode = new StringBody(model.getAuthorizedOrgsCode(), ContentType.APPLICATION_JSON);
        StringBody count = new StringBody(model.getCount(), ContentType.APPLICATION_JSON);
        StringBody licenseFileType = new StringBody(model.getLicenseFileType(), ContentType.APPLICATION_JSON);
        StringBody loanStage = new StringBody(model.getLoanStage(), ContentType.APPLICATION_JSON);
        StringBody caSupplier = new StringBody(Optional.<String>ofNullable(model.getCaSupplier()).orElse(""), ContentType.APPLICATION_JSON);
        StringBody validateUrl = new StringBody(Optional.<String>ofNullable(model.getValidateUrl()).orElse(""), ContentType.APPLICATION_JSON);
        StringBody authorizedStartTime = new StringBody(model.getAuthorizedStartTime(), ContentType.APPLICATION_JSON);
        StringBody authorizedEndTime = new StringBody(model.getAuthorizedEndTime(), ContentType.APPLICATION_JSON);
        BufferedInputStream inputStream = null;
        StringBody hashCode = null;
        boolean isFileWriteError = true;
        try {
            inputStream = FileUtil.getInputStream(file);
            hashCode = new StringBody(SmUtil.sm3(inputStream), ContentType.APPLICATION_JSON);
            isFileWriteError = false;
        } finally {
            if (ObjectUtil.isNotEmpty(inputStream)) {
                IoUtil.close(inputStream);
            }
        }
        if (isFileWriteError) {
            CountryPlatformResponse countryPlatformResponse = new CountryPlatformResponse();
            countryPlatformResponse.setRDesc("授权书读取文件异常！");
            countryPlatformResponse.setApiStatus(false);
            return countryPlatformResponse;
        }
        StringBody use = new StringBody(model.getQueryUse(), ContentType.APPLICATION_JSON);
        StringBody publickey = new StringBody(myPublicKey, ContentType.APPLICATION_JSON);
        FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA);
        StringBody tokenSrc = new StringBody(token, ContentType.APPLICATION_JSON);
        StringBody platformId = new StringBody(model.getPlatformId(), ContentType.APPLICATION_JSON);
        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("enterpriseName", (ContentBody) enterpriseName).addPart("uniscId", (ContentBody) uniscId).addPart("authorizedInfos", (ContentBody) authorizedInfos).addPart("authorizedOrgsCode", (ContentBody) authorizedOrgsCode).addPart("count", (ContentBody) count).addPart("platformId", (ContentBody) platformId).addPart("loanStage", (ContentBody) loanStage).addPart("licenseFileType", (ContentBody) licenseFileType).addPart("use", (ContentBody) use).addPart("caSupplier", (ContentBody) caSupplier).addPart("validateUrl", (ContentBody) validateUrl).addPart("authorizedEndTime", (ContentBody) authorizedEndTime).addPart("authorizedStartTime", (ContentBody) authorizedStartTime).addPart("hashCode", (ContentBody) hashCode).addPart("publicKey", (ContentBody) publickey).addPart("token", (ContentBody) tokenSrc).addPart("file", (ContentBody) fileBody).build();
        httpPost.setEntity(reqEntity);
        try {
            CloseableHttpResponse response = httpClient.execute((ClassicHttpRequest) httpPost);
            responseStr = EntityUtils.toString(response.getEntity(), "utf-8");
            log.info("返回结果" + responseStr);
            JSONObject jsonObject = JSONObject.parseObject(responseStr);
            String result = jsonObject.getString("C-API-Status");
            CountryPlatformResponse countryPlatformResponse = (CountryPlatformResponse) Optional.<Object>ofNullable(jsonObject.getObject("C-Response-Body", CountryPlatformResponse.class)).orElse(new CountryPlatformResponse());
            if (StringUtils.equals("00", result)) {
                countryPlatformResponse.setApiStatus(true);
                SM2 sm2 = SmUtil.sm2(myPrivateKey, myPublicKey);
                String responseData = HanDanBean.dealResult(sm2, countryPlatformResponse);
                log.info("结果:::::" + responseData);
                JSONObject responseDataJson = JSONObject.parseObject(responseData);
                countryPlatformResponse.setData(responseDataJson.getString("licenseId"));
            } else {
                countryPlatformResponse.setApiStatus(false);
            }
            countryPlatformResponse.setRDesc(jsonObject.getString("C-Response-Desc"));
            return countryPlatformResponse;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}


/* Location:              D:\tuodayun\workspace\work\celoan-third-data-report-service-2.0.0-SNAPSHOT.jar!\BOOT-INF\classes\com\celoan\handanUtils\HanDanHttpSelectUtils.class
 * Java compiler version: 8 (52.0)
 * JD-Core Version:       1.1.3
 */
